import { NestFactory } from '@nestjs/core';
import { GatewayModule } from './gateway.module';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import {
  aggregateSwaggerDocuments,
  excludeModulePaths,
} from '@app/utils/swaggerIntegrate';
import { NacosConfigService } from '@app/nacos-config';
import { NacosRegisterService } from '@app/nacos-register';
import { EtcdConfigService } from '@app/etcd-config';
import { EtcdRegisterService } from '@app/etcd-register';

async function bootstrap() {
  const app = await NestFactory.create(GatewayModule);
  /**
   * 配置中心&&注册中心
   */
  // 配置中心 nacos
  const nacosConfig = app.get(NacosConfigService);
  await nacosConfig.updateNacosConfig();
  // 注册中心 nacos
  const nacosService = app.get(NacosRegisterService);
  setTimeout(async () => {
    await nacosService.registerService('gateway-service'); //注册服务
    // nacosService.keepHealthyService(); //服务健康监控
  }, 0);

  // 配置中心 etcd
  const etcdConfig = app.get(EtcdConfigService);
  await etcdConfig.updateEtcdConfig();
  // 注册中心 etcd
  const etcdService = app.get(EtcdRegisterService);
  setTimeout(async () => {
    await etcdService.registerService('gateway-service'); //注册服务
    // nacosService.keepHealthyService(); //服务健康监控
  }, 0);

  app.enableShutdownHooks();

  /**
   * 网关聚合文档
   */
  const config = new DocumentBuilder()
    .setTitle('网关聚合API文档')
    .setDescription('Gateway网关聚合swagger文档')
    .setVersion('1.0')
    .addBearerAuth({
      type: 'http',
      description: '基于 jwt 的认证',
    })
    .build();
  // 创建 API Gateway 自身的 Swagger 文档，但过滤掉不需要的路由
  const gatewayDoc = SwaggerModule.createDocument(app, config, {
    ignoreGlobalPrefix: true,
    include: [], // 只包含指定的模块，空数组表示不包含任何模块
  });
  // 过滤 Gateway Swagger 文档 的所有模块
  excludeModulePaths(gatewayDoc, 'api');
  // 聚合其他微服务的Swagger文档
  await aggregateSwaggerDocuments(app, gatewayDoc);

  await app.listen(8000);

  /**
   * 关闭服务并注销
   */
  process.on('SIGINT', async () => {
    // 注销服务nacos
    await nacosService.romoveService('gateway-service');
    // 注销服务etcd
    await etcdService.romoveService('gateway-service');
    process.exit(0);
  });
}
bootstrap();
